<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '服务器设置',
    navigationBarBackgroundColor: '#1989fa',
    navigationBarTextStyle: 'white',
  },
}
</route>
<template>
  <Loyout class="server-page" bgc="#F3F8FE">
    <view class="link-box">
      <wd-form ref="form" :model="userInfo">
        <wd-cell-group border>
          <wd-input
            type="text"
            v-model="userInfo.ip"
            label="IP"
            placeholder="请输入"
            prop="ip"
            :rules="[
              {
                required: false,
                pattern: /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/,
                message: '请输入ip',
              },
            ]"
          />
          <wd-input
            type="text"
            v-model="userInfo.port"
            prop="port"
            label="端口"
            placeholder="请输入"
            :rules="[
              {
                required: false,
                type: 'number',
                min: 1,
                max: 65535,
                message: '请输入ip',
              },
            ]"
          />
          <!-- <wd-input type="text" label="开启无线上传" placeholder="请输入..." /> -->
        </wd-cell-group>
      </wd-form>
    </view>
    <template #footer>
      <wd-button class="flex1" size="large" @click="testNetwork">测试网络</wd-button>
      <wd-button class="flex1 ml-20" size="large" @click="saveUserInfo">保 存</wd-button>
    </template>
  </Loyout>
</template>

<script lang="ts" setup>
import Loyout from '@/layouts/index.vue'
import { useUserStore } from '@/store/user'
import { useToast } from 'wot-design-uni'
import { useSocket } from '@/utils/socket'
const Toast = useToast()
const userStore = useUserStore()
const form = ref()
const userInfo = computed(() => userStore.userInfo)

const testNetwork = async () => {
  try {
    await form.value.validate()
    // fetch(`http://${userInfo.value.ip}:${userInfo.value.port}`)
    //   .then((res) => res.json())
    //   .then((res) => {
    //     console.log('res', res)
    //   })
    //   .catch((err) => {
    //     console.log('err', err)
    //   })
    const socket = await useSocket()
    socket.closess()
    setTimeout(async () => {
      await useSocket()
      Toast.success('连接成功')
    }, 1000)
  } catch (error) {
    console.log('error', error)
  }
}

const saveUserInfo = async () => {
  await form.value.validate()
  userStore.setUserInfo(userInfo.value)
  Toast.success('成功')
}
</script>
